package com.ppt.convert.service;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.ppt.convert.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author zcx
 * @Title word转化
 * @date 2020年07月01日 15:42
 **/
@Service
public class WordConvertService {

    @Value("${file.preAbsoluteFolder}")
    private String preAbsoluteFolder;

    @Value("${file.afterAbsoluteFolder}")
    private String afterAbsoluteFolder;

    @Autowired
    private DownLoadService downLoadService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private PdfConvertService pdfConvertService;

    private static final Logger logger = LoggerFactory.getLogger(WordConvertService.class);

    /**
     * word图片转换
     * @author zcx
     * @date 2020-07-01 16:00
     * @param dentryId 文件id
     * @param companyId 机构id
     * @param fileUrl 网盘地址
     * @param fileName 文件名
     * @return com.ppt.convert.domain.Result
     */
    public Result wordConvert(String dentryId, String companyId, String fileUrl, String fileName) {
        //要转换的源文件地址
        String fromPath = afterAbsoluteFolder + "download_cqt" + File.separator + dentryId + File.separator + fileName;
        //要转换的源文件父级目录
        String parrentPath = afterAbsoluteFolder + "download_cqt" + File.separator + dentryId;
        //要转换的路径
        String afterPath = afterAbsoluteFolder + "convert_img" + File.separator + dentryId;
        File file = new File(afterPath);
        if(!file.exists()){
            file.mkdirs(); //创建目录
        }
        logger.info("网盘下载开始---------------------------------------");
        Result result = downLoadService.downLoadFile(parrentPath, fileUrl, dentryId, fileName);
        if (result.getResp_code() == 1) {
            return Result.failed("从网盘下载文件下来失败了----------------");
        }
        logger.info("网盘下载结束---------------------------------------");
        String name = fileName.substring(fileName.lastIndexOf(".") + 1);
        //要转化的pdf的路径
        String pdfFromPath = parrentPath+ File.separator + name+".pdf";
        //先将word转为pdf然后转为图片
        Result wordToPDFResult = wordToPDF(fromPath,pdfFromPath);
        if(wordToPDFResult.getResp_code()==1) {
            return wordToPDFResult;
        }else {
            return pdfConvertService.pdfToImage(parrentPath,pdfFromPath,afterPath, dentryId, companyId, 1f);
        }
    }

    /**
     * word转pdf
     * @author zcx
     * @date 2020-07-01 15:59
     * @param fromPath 要转的word
     * @param afterPater 转化后pdf路径
     * @return com.ppt.convert.domain.Result
     */
    public Result wordToPDF(String fromPath, String afterPater) {
        logger.info("启动 Word...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", fromPath).toDispatch();
            logger.info("打开文档..." + fromPath);
            logger.info("转换文档到 PDF..." + afterPater);
            File tofile = new File(afterPater);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", afterPater, // FileName
                    17);
            long end = System.currentTimeMillis();
            logger.info("转换完成..用时：" + (end - start) + "ms.");
        } catch (Exception e) {
            logger.info("========Error:文档转换失败：" + e.getMessage());
            Result.failed("========Error:文档转换失败：" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            logger.info("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[] {});
        }
        // 如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
        return Result.succeed("转化word文档成功");
    }
}
